/**
 * 
 */
package networkinterface;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Michael & Pierre
 */
/**
 * Thread used to receive a file
 */
public class ReceiveFileThread extends Thread {
	
	private static JavaNI javaNI;
	
	private int port;
	/**
	 * File which will be received
	 */
	private File recvFile;
	
	/**
	 * 
	 * @param destDirectory Directory where the received file will be stored
	 * @param port local port where the file will be received
	 * @param javaNI network interface of the system
	 */
	public ReceiveFileThread(String destDirectory, int port, JavaNI javaNI) {
		this.port = port;
		ReceiveFileThread.javaNI = javaNI;
		recvFile = new File(destDirectory);
	}
	
	public void run() {
		ServerSocket serverSocket;
		BufferedOutputStream outFile = null;
		BufferedInputStream inFile;
		
		try {
			
			serverSocket = new ServerSocket(port);
			Socket mySocket = serverSocket.accept();
			
			inFile = new BufferedInputStream(mySocket.getInputStream());
			outFile = new BufferedOutputStream(new FileOutputStream(recvFile));
			
			byte[] octets = new byte[1024];
			int num;
			while ((num = inFile.read(octets, 0, 1024)) != -1) {
			  outFile.write(octets, 0, num);
			}
			outFile.flush();
			outFile.close();
			mySocket.close();
			serverSocket.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (outFile != null) {
				outFile.flush();
				outFile.close();	
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
                        javaNI.fileRcvd();
		}
	}
}
